import gen.YYParser;
import bison.LexToken;

import flash.display.Sprite;
import flash.text.TextField;

class FlashMain extends Sprite
{
   var results:TextField;
   var input:TextField;
   var lexer:MyLexer;
   var parser:YYParser;
   var htmlText:String;

   public function new()
   {
      htmlText = "<b>Calc - haxe/bison based calculator</b><br>" +
                 "Type into lower box<br>" +
                 " eg: x = cos(PI)+0x20/3.2<br>";
      super();
      results = new TextField( );
      results.x = 10;
      results.y = 10;
      results.width = 400;
      results.height = 400;
      results.multiline = true;
      results.htmlText = htmlText;
      results.border = true;
      results.background = true;
      results.backgroundColor = 0xffffff;
      addChild(results);

      input = new TextField( );
      input.x = 10;
      input.y = 420;
      input.height = 24;
      input.width = 400;
      input.text = "";
      input.border = true;
      input.background = true;
      input.backgroundColor = 0xffffff;
      input.type = flash.text.TextFieldType.INPUT;
      input.addEventListener(flash.events.KeyboardEvent.KEY_UP, onKey);
      addChild(input);

      var symbols = new Hash<Float>();
      symbols.set("PI",Math.PI);
      YYParser.errorVerbose = true;
      lexer = new MyLexer(null);
      parser = new YYParser(null,symbols);
      parser.errorFunction = function(message:String,info:Dynamic)
      {
         htmlText += "<font color='#ff0000'>" + message + (info==null?"":" "+info) + "</font><br>";
         results.htmlText = htmlText;
         results.scrollV = results.maxScrollV;
         return YYParser.YYERROR;
      }
      parser.output = function(s:String)
      {
         htmlText += "<b>" + s + "</b><br>";
         results.htmlText = htmlText;
         results.scrollV = results.maxScrollV;
      }

      flash.Lib.current.addChild(this);
      stage.focus = input;
   }

   function onKey(e:flash.events.KeyboardEvent)
   {
      if (e.charCode==13)
      {
         var txt = input.text;
         input.text = "";
         if (txt!="")
         {
           htmlText+=txt+"<br>";
           results.htmlText = htmlText;
           txt+="\n";
           // Run the parser in reverse mode, ie push tokens to parser
           lexer.parseInput(parser,txt);
         }
      }
   }

   public static function main()
   {
      new FlashMain();
   }
}

